<template>
  <div class="login">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" show-password></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getLogin,getMenus } from "../utils/api";
import {fn} from '../utils/routeList.js';
export default {
  data() {
    return {
      ruleForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
          // getLogin(this.ruleForm).then((res) => {
          //   if (res.meta.status == 200) {
          //     localStorage.setItem("token", res.data.token);
          //   }
          //   this.$router.push("/");
          // });
          this.$store.dispatch('setLogin',this.ruleForm).then(res=>{
            if(res.meta.status===200){
              this.$router.push('/')
              this.loadRoute()
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //动态路由方法
    async loadRoute() {
      let res = await getMenus()
      if (res.meta.status === 200) {
        localStorage.setItem("menusList", JSON.stringify(res.data))
        let newList = fn(res.data)
        console.log("递归后的列表路由", newList)
        newList.forEach((item) => {
          this.$router.addRoute("Home", item)
        })
      }
    },


  }
};
</script>
<style scoped lang="scss">
.login {
  width: 500px;
  height: 500px;
  margin: 100px auto;
}
</style>